package com.socialuni.sdk.domain;

import com.socialuni.sdk.model.DO.user.AccountDO;
import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.manage.CommonUserAccountDOCreate;
import com.socialuni.sdk.manage.CommonUserAccountDOGet;
import com.socialuni.sdk.user.userManage.SocialUserManage;
import com.socialuni.sdk.model.ProviderLoginQO;
import com.socialuni.sdk.utils.UserUtils;
import com.socialuni.sdk.exception.UniSdkException;
import com.socialuni.sdk.model.UniUnionIdRO;
import com.socialuni.sdk.utils.UniProviderUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserProviderLoginDomain {
    @Resource
    SocialUserManage uniUserDOCreate;
    @Resource
    CommonUserAccountDOGet uniUserAccountDOGet;
    @Resource
    CommonUserAccountDOCreate uniUserAccountDOCreate;

    //根据渠道登录信息获取user
    public UserDO getOrCreate(ProviderLoginQO loginQO) {
        UniUnionIdRO uniUnionIdRO = UniProviderUtil.getUnionIdRO(loginQO);
        if (uniUnionIdRO.hasError()){
            throw new UniSdkException("获取openId失败");
        }
        return getOrCreate(loginQO, uniUnionIdRO);
    }

    public UserDO getOrCreate(ProviderLoginQO loginQO, UniUnionIdRO uniUnionIdRO) {
        AccountDO accountDO = uniUserAccountDOGet.getAccountByUnionId(loginQO, uniUnionIdRO);
        UserDO userDO;
        //如果已经注册过
        if (accountDO != null) {
            userDO = UserUtils.get(accountDO.getUserId());
        } else {
            userDO = this.create(loginQO, uniUnionIdRO);
        }
        return userDO;
    }

    public UserDO create(ProviderLoginQO loginQO, UniUnionIdRO uniUnionIdRO) {
        UserDO userDO = uniUserDOCreate.createUserByProviderLogin(loginQO);
        uniUserAccountDOCreate.create(userDO, loginQO, uniUnionIdRO);
        return userDO;
    }
}
